#include "communication-device-sensor.h"

CommunicationDeviceSensor::CommunicationDeviceSensor(SmartDeviceManager *manager)
    : smartDeviceManager(manager)
{
	handle["add"]    = &CommunicationDeviceSensor::add;
	handle["remove"] = &CommunicationDeviceSensor::remove;
	handle["query"]  = &CommunicationDeviceSensor::query;
}

void CommunicationDeviceSensor::communication(SmartDevicenetProtocol &netProtocol, NetCommunication *netObj)
{
	//1控制门锁
	string command = netProtocol.getCommand();
	auto   func    = handle[command];
	if(!func)
	{
		return;
	}
	(this->*func)(netProtocol, netObj);
}

void CommunicationDeviceSensor::add(SmartDevicenetProtocol &netProtocol,
                                    NetCommunication *      netObj)
{
	SmartDeviceDatabase *smartDeviceDatabase = SmartDeviceDatabase::getSmartDeviceDatabase();
	bool                 ok                  = smartDeviceDatabase->addDevice(
        netProtocol.getOperation(),
        netProtocol.getDeviceValue("deviceType"),
        netProtocol.getDeviceValue("deviceNumber"));

	string errmsg = ok ? "" : "error";
	//等待锁那边回复 UDP发送
	replay(netObj, netProtocol.getCommand(), errmsg);
}

void CommunicationDeviceSensor::remove(SmartDevicenetProtocol &netProtocol,
                                       NetCommunication *      netObj)
{
	SmartDeviceDatabase *smartDeviceDatabase = SmartDeviceDatabase::getSmartDeviceDatabase();
	bool                 ok                  = smartDeviceDatabase->removeDevice(
        netProtocol.getOperation(),
        netProtocol.getDeviceValue("deviceType"),
        netProtocol.getDeviceValue("deviceNumber"));

	string errmsg = ok ? "" : "error";
	//等待锁那边回复 UDP发送
	replay(netObj, netProtocol.getCommand(), errmsg);
}

void CommunicationDeviceSensor::query(SmartDevicenetProtocol &netProtocol, NetCommunication *netObj)
{
	string   command      = netProtocol.getCommand();
	uint32_t deviceType   = netProtocol.getDeviceType();
	uint32_t deviceNumber = netProtocol.getDeviceNumber();
	uint16_t sensorData;
	bool     ok = smartDeviceManager->querySensor(deviceType, deviceNumber, sensorData);

	string errmsg = ok ? "" : "error";
	string data   = ok ? to_string(sensorData) : "0x00";
	replay(netObj, command, errmsg, data);
	return;
}

void CommunicationDeviceSensor::replay(NetCommunication *netObj,
                                       const string &    command,
                                       const string &    errmsg,
                                       const string &    data)
{
	SmartDevicenetProtocol netProtocol;
	netProtocol.addOperation("sensor");
	netProtocol.addCommand(command);
	netProtocol.addResult(errmsg, data);
	string repalyJsonData = netProtocol.toString();

	vector<uint8_t> packet;
	packet.assign(repalyJsonData.begin(), repalyJsonData.end());
	cout << "------------udp发送----------------" << endl;
	bool ret = netObj->sendPacket(packet);
	if(ret != true)
	{
		fprintf(stderr, "Fail to sendPacket\n");
		return;
	}

	return;
}
